package com.atguigu.jdbc;

import java.sql.*;

/**
 * projectName: day04_jdbc
 *
 * @author: 赵伟风
 * time: 2021/11/26 15:52
 * description:jdbc操作返回插入数据的主键列
 */
public class ReturnKeys {


    public static void main(String[] args) throws ClassNotFoundException, SQLException {

       //1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");

       //2.获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql:///test1", "root", "root");

        //3.sql结构
        String sql = "insert into user (nickname,account,password) values (?,?,?)";

       //4.预编译动态statement
        //设置想要获取返回生成keys
        PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        //5.占位符赋值
        statement.setObject(1, "吴邪");
        statement.setObject(2, "wuxie1");
        statement.setObject(3, "root");

       //6.执行sql
        int rows = statement.executeUpdate();

        //返回主键值 单行单列
        ResultSet generatedKeys = statement.getGeneratedKeys();

        if (rows >0) {
            System.out.println("注册成功！");

            generatedKeys.next();

            int key = generatedKeys.getInt(1);

            System.out.println("key = " + key);

        }


        //7.关闭资源

        statement.close();
        connection.close();

    }


}
